package demo1;

import java.util.Arrays;

public class MyArrayList {
    private int[] elem;//存储数据
    private int usedSize;//当前顺序表中有效数据,不受最大容量的影响

    private static final int DEFAULT_SIZE = 10;

    //无参构造函数，设定默认值
    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    //有参构造函数，用于设定指定值
    public MyArrayList(int initCapacity) {
        this.elem = new int[initCapacity];
    }

    //打印顺序表
    public void display() {
        for (int i = 0; i < usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
    }

    //添加新增元素，默认在最后
    public void add(int data) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);//扩容
        }
        this.elem[usedSize] = data;
        usedSize++;
    }

    //判断是否满了
    public boolean isFull() {
        if (this.usedSize == this.elem.length) {
            return true;
        }
        return false;
    }

    //在pos位置增加元素
    public void add(int pos, int data) {
        if (pos < 0 || pos > this.usedSize) {
            throw new PosOutOfBoundsException(pos + "位置不合法!");
        }
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);//扩容
        }
        for (int i = this.usedSize - 1; i >= pos; i--) {
            this.elem[i + 1] = this.elem[i];
        }
        this.elem[pos] = data;
        usedSize++;
    }

    //判定是否包含某个元素
    public boolean contains(int toFind) {
        //如果判断为引用类型，则使用equals
        for (int i = 0; i < usedSize; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    //查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    //获取pos位置的元素
    public int get(int pos) {
        checkPos(pos);
        return this.elem[pos];
    }

    //给pos位置设置元素value
    public void set(int pos , int value) {
        checkPos(pos);
        this.elem[pos] = value;
    }

    //检查pos位置是否合法
    private void checkPos(int pos){
        if (pos < 0 || pos > this.usedSize) {
            throw new PosOutOfBoundsException(pos + "位置不合法!");
        }
    }

    //获取顺序表长度
    public int size() {
        return usedSize;
    }

    //删除第一次出现的关键字key
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        if(index == -1) {
            System.out.println("没有这个数据");
            return;
        }
        for (int i = index; i < this.usedSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        this.usedSize--;
    }

    //清空顺序表
    public void clear(){
        this.usedSize = 0;
    }
}